package com.boc.ewr.uniapp.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boc.ewr.bcimp.entity.BusAcctInfo;
import com.boc.ewr.bcimp.entity.CusmTagList;
import com.boc.ewr.bcimp.service.IBusAcctInfoService;
import com.boc.ewr.business.entity.AcctClassAFdbk;
import com.boc.ewr.business.entity.AcctDtlClassA1;
import com.boc.ewr.business.entity.CaCusmCallOlfdbk;
import com.boc.ewr.clkIn.entity.CaDtdClkin;
import com.boc.ewr.uniapp.api.service.IBusCusmInfoApiService;
import com.boc.ewr.uniapp.api.vo.AcctInfoVo;
import com.boc.ewr.uniapp.api.vo.BusAcctInfoVo;
import com.boc.ewr.uniapp.api.vo.CaRecordVo;
import com.boc.ewr.uniapp.api.vo.TagReqVo;
import com.boc.ewr.work.entity.WorkRecordDtl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : Wzz
 * @create : 2023-05- 30- 17:25
 * @desc :
 */

@Api(tags = "客户档案查询Api")
@RestController
@RequestMapping("/uniapp/cusm/info")
@Slf4j
public class BusCusmInfoApiController {

    @Autowired
    private IBusAcctInfoService busAcctInfoService;

    @Autowired
    private IBusCusmInfoApiService busCusmInfoApiService;

    @ApiOperation(value = "客户档案查询Api-列表查询", notes = "客户档案查询Api-列表查询")
    @GetMapping(value = "/queryPageList")
    public Result<IPage<BusAcctInfoVo>> queryPageList(BusAcctInfo busAcctInfo,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<BusAcctInfo> busAcctInfoQueryWrapper = QueryGenerator.initQueryWrapper(busAcctInfo, req.getParameterMap());

        // 根据用户名去重，同时返回最早开户账户对应数据的Id
        busAcctInfoQueryWrapper.select("*")
                .inSql("id", "SELECT id FROM bus_acct_info WHERE (cusm_nm, oacct_date) IN (SELECT cusm_nm, MIN(oacct_date) FROM bus_acct_info GROUP BY cusm_nm)")
                .orderByAsc("cusm_nm");
        Page<BusAcctInfo> page = new Page<BusAcctInfo>(pageNo, pageSize);
        IPage<BusAcctInfo> pageList = busAcctInfoService.page(page, busAcctInfoQueryWrapper);
        IPage<BusAcctInfoVo> convertIPage = this.convertBusInfoPage(pageList);
        return Result.OK(convertIPage);
    }

    @ApiOperation(value = "客户档案查询Api-根据公司名模糊查询", notes = "客户档案查询Api-根据公司名模糊查询")
    @GetMapping(value = "/queryPageLike")
    public Result<IPage<BusAcctInfoVo>> queryPageLike(BusAcctInfo busAcctInfo,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      @RequestParam(name = "likeWord", defaultValue = "") String likeWord,
                                                      HttpServletRequest req) {
        QueryWrapper<BusAcctInfo> busAcctInfoQueryWrapper = QueryGenerator.initQueryWrapper(busAcctInfo, req.getParameterMap());
        // 模糊查询匹配客户名称
        busAcctInfoQueryWrapper.like("cusm_nm", likeWord);
        // 根据用户名去重，同时返回最早开户账户对应数据的Id
        busAcctInfoQueryWrapper.select("*")
                .inSql("id", "SELECT id FROM bus_acct_info WHERE (cusm_nm, oacct_date) IN (SELECT cusm_nm, MIN(oacct_date) FROM bus_acct_info GROUP BY cusm_nm)")
                .orderByAsc("cusm_nm");
        Page<BusAcctInfo> page = new Page<BusAcctInfo>(pageNo, pageSize);
        IPage<BusAcctInfo> pageList = busAcctInfoService.page(page, busAcctInfoQueryWrapper);
        IPage<BusAcctInfoVo> convertIPage = this.convertBusInfoPage(pageList);
        return Result.OK(convertIPage);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "客户档案查询Api-通过id查询")
    @ApiOperation(value = "客户档案查询Api-通过id查询", notes = "客户档案查询Api-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BusAcctInfoVo> queryById(@RequestParam(name = "id", required = true) String id) {
        BusAcctInfo busAcctInfo = busAcctInfoService.getById(id);
        if (busAcctInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(this.convertBusInfo(busAcctInfo));
    }

    //@AutoLog(value = "客户档案查询Api-通过CusmNm查询标签")
    @ApiOperation(value = "客户档案查询Api-通过CusmNm查询标签", notes = "客户档案查询Api-通过CusmNm查询标签")
    @GetMapping(value = "/queryTageByCusmNm")
    public Result<Map<String, List<CusmTagList>>> queryTageByCusmNm(@RequestParam(name = "CusmNm", required = true) String CusmNm) {
        Map<String, List<CusmTagList>> map = busCusmInfoApiService.queryTageByCusmNm(CusmNm);

        return Result.OK(map);
    }

    //@AutoLog(value = "客户档案查询Api-通过CusmNm刷新标签")
    @ApiOperation(value = "客户档案查询Api-通过CusmNm刷新标签", notes = "客户档案查询Api-通过CusmNm刷新标签")
    @GetMapping(value = "/updateTagByCusmNm")
    public Result<String> updateTagByCusmNm(@RequestParam(name = "CusmNm", required = true) String CusmNm) {
        busCusmInfoApiService.updateTagByCusmNm(CusmNm);

        return Result.OK("标签刷新成功");
    }


    //@AutoLog(value = "客户档案查询Api-网点新增自定义标签")
    @ApiOperation(value = "客户档案查询Api-网点新增自定义标签", notes = "客户档案查询Api-网点新增自定义标签")
    @RequestMapping(value = "/addOrgDiyTag", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> addOrgDiyTag(@RequestBody TagReqVo tagReqVo) {
        busCusmInfoApiService.addOrgDiyTag(tagReqVo);

        return Result.OK("标签添加成功");
    }


    //@AutoLog(value = "客户档案查询Api-网点删除自定义标签")
    @ApiOperation(value = "客户档案查询Api-网点删除自定义标签", notes = "客户档案查询Api-网点删除自定义标签")
    @DeleteMapping("/removeOrgDiyTag")
    public Result<String> removeOrgDiyTag(@RequestBody TagReqVo tagReqVo) {
        /*if (tagReqVo.getCreateOrgNo().equals(this.getLoginUser().getOrgCode())) {
            return Result.error("不能移除非本机构添加的标签！");
        }*/

        busCusmInfoApiService.removeOrgDiyTag(tagReqVo);

        return Result.OK("标签删除成功");
    }


    //@AutoLog(value = "客户档案查询Api-查询账户列表")
    @ApiOperation(value = "客户档案查询Api-查询账户列表", notes = "客户档案查询Api-查询账户列表")
    @GetMapping("/getAcctInfoByCusmName")
    public Result<List<AcctInfoVo>> getAcctInfoByCusmName(@RequestParam(name = "cusmNm", required = true) String cusmNm) {

        List<AcctInfoVo> voList = busCusmInfoApiService.getAcctInfoByCusmName(cusmNm);

        return Result.OK(voList);
    }


    //@AutoLog(value = "客户档案查询Api-获取最近一次的联系记录")
    @ApiOperation(value = "客户档案查询Api-获取最近一次的联系记录", notes = "客户档案查询Api-获取最近一次的联系记录")
    @GetMapping("/getLatestCall")
    public Result<WorkRecordDtl> getLatestCall(@RequestParam(name = "cusmNm", required = true) String cusmNm) {

        WorkRecordDtl workRecordDtl = busCusmInfoApiService.getLatestCallByCusmNm(cusmNm);

        return Result.OK(workRecordDtl);
    }


    //@AutoLog(value = "客户档案查询Api-查询最近一次上门拍摄照片（外出打卡记录）")
    @ApiOperation(value = "客户档案查询Api-查询最近一次上门拍摄照片（外出打卡记录）", notes = "客户档案查询Api-查询最近一次上门拍摄照片（外出打卡记录）")
    @GetMapping("/getLatestDtdPhoto")
    public Result<CaDtdClkin> getLatestDtdPhoto(@RequestParam(name = "cusmNm", required = true) String cusmNm) {

        CaDtdClkin caDtdClkin = busCusmInfoApiService.getLatestDtdPhoto(cusmNm);

        return Result.OK(caDtdClkin);
    }

    // 查询对账记录（从A1,A2,A3查出来再返回实体类 A类汇总）
    // 客户档案详情--对账历史记录只需要最新一次的记录、展示的内容：协议号、对账月份
    //@AutoLog(value = "客户档案查询Api-查询对账记录")
    @ApiOperation(value = "客户档案查询Api-查询对账记录", notes = "客户档案查询Api-查询对账记录")
    @GetMapping("/getCaRecordByCusmNm")
    public Result<CaRecordVo> getCaRecordByCusmNm(@RequestParam(name = "cusmNm", required = true) String cusmNm) {
        // 只展示最近一次的对账记录
        CaRecordVo caRecordVo = busCusmInfoApiService.getCaRecordByCusmNm(cusmNm);

        return Result.OK(caRecordVo);
    }


    /**
     * 将 对公账户信息Page转出成Vo的Page
     */
    public IPage<BusAcctInfoVo> convertBusInfoPage(IPage<BusAcctInfo> page) {
        List<BusAcctInfoVo> voList = page.getRecords().stream()
                .map(this::convertBusInfo)
                .collect(Collectors.toList());

        IPage<BusAcctInfoVo> voPage = new Page<>();
        voPage.setCurrent(page.getCurrent());
        voPage.setSize(page.getSize());
        voPage.setTotal(page.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }

    private BusAcctInfoVo convertBusInfo(BusAcctInfo entity) {
        BusAcctInfoVo vo = new BusAcctInfoVo();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    private LoginUser getLoginUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }
}
